package com.jiangyg.mall.seckill.scheduled;

import com.jiangyg.mall.seckill.constant.CacheConstant;
import com.jiangyg.mall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 类描述：秒杀定时任务
 *
 * @author jiangyg
 * @date 2022-01-03
 */
@Slf4j
@Component
public class SeckillScheduled {

    private final SeckillService seckillService;

    private final RedissonClient redissonClient;

    @Autowired
    public SeckillScheduled(SeckillService seckillService, RedissonClient redissonClient) {
        this.seckillService = seckillService;
        this.redissonClient = redissonClient;
    }

    /**
     * 功能描述：每天凌晨1点，执行秒杀商品上架任务
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void seckillUploadTask() throws Exception {
        // TODO 防幂等性处理不严谨，后期需要更换定时任务架构
        // TODO 场次过期删除操作
        // 1. 获取秒杀上架锁，防止重复上架
        final RLock lock = this.redissonClient.getLock(CacheConstant.SECKILL_UPDATE_LOCK_KEY);
        boolean success = false;
        try {
            success = lock.tryLock(5, 5, TimeUnit.SECONDS);
            seckillService.updateSeckillDataWithin3Days();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (success) {
                lock.unlock();
            }
        }
    }

}
